//
//  XJLAreaSelectedViewController.m
//  XJL_WeChat
//
//  Created by XJL on 16/7/31.
//  Copyright © 2016年 Xujiali. All rights reserved.
//

#import "XJLAreaSelectedViewController.h"

@interface XJLAreaSelectedViewController ()<UITableViewDataSource>

/** 国家区号数据 */
@property(nonatomic,strong) NSArray *countryTelCodePlist;

@end

@implementation XJLAreaSelectedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"选择国家和地区";
    
    //1.添加搜索控件
    UISearchBar *searchBar = [[UISearchBar alloc]init];
    searchBar.bounds = CGRectMake(0, 0, 320, 40);
    self.tableView.tableHeaderView = searchBar;
    
    //2.显示国家区号 数据
    //加载Plist文件
    NSURL *plistURL = [[NSBundle mainBundle]URLForResource:@"CountryTelCode" withExtension:@"plist"];
    self.countryTelCodePlist = [NSArray arrayWithContentsOfURL:plistURL];
    
    //3.添加返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:0 target:self action:@selector(back)];
    
}

-(void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
//表格的组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.countryTelCodePlist.count;
}

//表格的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    //获取相应组
    NSArray *sectionData = self.countryTelCodePlist[section];
    
    return sectionData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ID = @"CountryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    
    //1、获取组数据
    NSArray *sectionData = self.countryTelCodePlist[indexPath.section];
    
    //2、获取行数据
    NSArray *rowData = sectionData[indexPath.row];
    
    //3、获取地区/国家名字
    NSString *name = rowData[0];
    cell.textLabel.text = name;
    
    //4、获取区号
    NSString *code = rowData[1];
    cell.detailTextLabel.text = code;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //获取当前的国家名字和区号
    //1.1 获取组数据
    NSArray *sectionData = self.countryTelCodePlist[indexPath.section];
    //1.2 获取行数据
    NSArray *rowData = sectionData[indexPath.row];
    //1.3 获取地区/国家名字
    NSString *name = rowData[0];
    //获取区号
    NSString *code = rowData[1];
    
    //调用block，告诉上一个控制器，当前选择的名字和区号
    if (self.areaSelectFinish) {
        _areaSelectFinish(name,code);
    }
    
    [self back];
}

@end
